import { STORAGE_KEYS } from '@/constants/storage';
import { storageService } from '@/services/storage';
import type { OperationResult } from '@/types/common/base';
import type { 
  IScheduleTemplate, 
  IScheduleTemplateCreateRequest, 
  IScheduleTemplateUpdateRequest, 
  IScheduleTemplateQueryParams,
  IScheduleTemplateStatistics,
  IScheduleTemplateSummary,
  IScheduleTemplateDetail
} from '@/types/schedule/scheduleTemplate';
import type { 
  IScheduleInstance, 
  IScheduleInstanceCreateRequest, 
  IScheduleInstanceUpdateRequest, 
  IScheduleInstanceQueryParams,
  IScheduleInstanceStatistics,
  IScheduleInstanceSummary,
  IScheduleInstanceDetail,
  IScheduleInstanceConflict
} from '@/types/schedule/scheduleInstance';
import { 
  DayOfWeekEnum, 
  ScheduleTemplateStatusEnum, 
  ScheduleInstanceStatusEnum 
} from '@/types/schedule/enums';

/**
 * 课表验证结果接口
 */
interface IScheduleValidationResult {
  /** 是否验证通过 */
  isValid: boolean;
  /** 错误信息列表 */
  errors: string[];
}

/**
 * 冲突检测结果接口
 */
interface IConflictDetectionResult {
  /** 是否有冲突 */
  hasConflict: boolean;
  /** 冲突列表 */
  conflicts: IScheduleInstanceConflict[];
}

/**
 * 课表服务类
 * @description 负责课程安排模板和实例的增删改查和业务逻辑处理
 */
export class ScheduleService {
  // ==================== 课程安排模板相关方法 ====================

  /**
   * 获取所有课程安排模板
   * @param queryParams 查询参数
   * @returns 模板列表
   */
  async getAllTemplates(queryParams?: IScheduleTemplateQueryParams): Promise<OperationResult<IScheduleTemplate[]>> {
    try {
      const result = await storageService.getItem<IScheduleTemplate[]>(STORAGE_KEYS.SCHEDULE_TEMPLATES);
      
      if (!result.success) {
        // 如果没有数据，返回空数组
        if (result.errorCode === 'INVALID_DATA_FORMAT') {
          return {
            success: true,
            data: []
          };
        }
        return result;
      }

      let templates = result.data || [];

      // 过滤已删除的模板
      templates = templates.filter(template => template.status !== ScheduleTemplateStatusEnum.DELETED);

      // 应用查询参数
      if (queryParams) {
        templates = this.filterTemplates(templates, queryParams);
      }

      return {
        success: true,
        data: templates
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程安排模板列表失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据ID获取课程安排模板
   * @param id 模板ID
   * @returns 模板信息
   */
  async getTemplateById(id: string): Promise<OperationResult<IScheduleTemplate>> {
    try {
      const templatesResult = await this.getAllTemplates();
      if (!templatesResult.success) {
        return templatesResult;
      }

      const template = templatesResult.data.find(t => t.id === id);
      if (!template) {
        return {
          success: false,
          error: '课程安排模板不存在'
        };
      }

      return {
        success: true,
        data: template
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程安排模板信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取课程安排模板详情
   * @param id 模板ID
   * @returns 模板详情
   */
  async getTemplateDetail(id: string): Promise<OperationResult<IScheduleTemplateDetail>> {
    try {
      const templateResult = await this.getTemplateById(id);
      if (!templateResult.success) {
        return templateResult;
      }

      const template = templateResult.data;

      // 获取关联的学生信息
      const studentResult = await storageService.getItem<any[]>(STORAGE_KEYS.STUDENTS);
      const students = studentResult.success && studentResult.data ? studentResult.data : [];
      const student = students.find((s: any) => s.id === template.studentId);

      // 获取关联的课程信息
      const courseResult = await storageService.getItem<any[]>(STORAGE_KEYS.COURSES);
      const courses = courseResult.success && courseResult.data ? courseResult.data : [];
      const course = courses.find((c: any) => c.id === template.courseId);

      // 获取课程实例
      const instancesResult = await this.getInstancesByTemplate(id);
      const instances = instancesResult.success ? instancesResult.data : [];

      // 计算剩余次数
      const remainingCount = template.totalCount - template.completedCount;

      // 计算下次上课日期
      const nextSessionDate = this.calculateNextSessionDate(template, instances);

      // 获取最近一次上课日期
      const completedInstances = instances.filter(inst => inst.status === ScheduleInstanceStatusEnum.COMPLETED);
      const lastSessionDate = completedInstances.length > 0 
        ? completedInstances.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())[0].date
        : undefined;

      const templateDetail: IScheduleTemplateDetail = {
        ...template,
        student: student ? {
          id: student.id,
          name: student.name,
          studentId: student.studentId,
          phone: student.phone
        } : {
          id: template.studentId,
          name: '未知学生',
          studentId: '',
          phone: undefined
        },
        course: course ? {
          id: course.id,
          name: course.name,
          courseCode: course.courseCode,
          teacher: course.teacher,
          color: course.color
        } : {
          id: template.courseId,
          name: '未知课程',
          courseCode: '',
          teacher: '',
          color: '#1890ff'
        },
        remainingCount,
        nextSessionDate,
        lastSessionDate,
        instances: instances.map(inst => ({
          id: inst.id,
          date: inst.date,
          status: inst.status.toString()
        }))
      };

      return {
        success: true,
        data: templateDetail
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程安排模板详情失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 创建课程安排模板
   * @param templateData 模板数据
   * @returns 创建的模板信息
   */
  async createTemplate(templateData: IScheduleTemplateCreateRequest): Promise<OperationResult<IScheduleTemplate>> {
    try {
      // 数据验证
      const validationResult = this.validateTemplateData(templateData);
      if (!validationResult.isValid) {
        return {
          success: false,
          error: validationResult.errors.join('; ')
        };
      }

      // 验证学生和课程是否存在
      const entityValidationResult = await this.validateStudentAndCourse(templateData.studentId, templateData.courseId);
      if (!entityValidationResult.success) {
        return entityValidationResult;
      }

      // 检查时间冲突
      const conflictResult = await this.checkTemplateConflict(templateData);
      if (!conflictResult.success) {
        return conflictResult;
      }

      if (conflictResult.data.hasConflict) {
        return {
          success: false,
          error: `时间冲突：${conflictResult.data.conflicts.map(c => c.description).join('; ')}`
        };
      }

      // 获取现有模板列表
      const templatesResult = await this.getAllTemplates();
      if (!templatesResult.success) {
        return templatesResult;
      }

      const templates = templatesResult.data;

      // 计算结束日期
      const endDate = this.calculateEndDate(templateData.startDate, templateData.dayOfWeek, templateData.totalCount);

      // 创建新模板对象
      const now = Date.now();
      const newTemplate: IScheduleTemplate = {
        id: this.generateTemplateId(),
        ...templateData,
        completedCount: 0,
        cancelledCount: 0,
        currentMakeupCount: 0,
        endDate,
        status: templateData.status || ScheduleTemplateStatusEnum.ACTIVE,
        allowMakeup: templateData.allowMakeup ?? true,
        createdAt: now,
        updatedAt: now
      };

      // 添加到模板列表
      templates.push(newTemplate);

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.SCHEDULE_TEMPLATES, templates, {
        createBackup: true
      });

      if (!saveResult.success) {
        return saveResult;
      }

      // 生成课程实例
      const generateResult = await this.generateInstances(newTemplate.id);
      if (!generateResult.success) {
        console.warn('生成课程实例失败:', generateResult.error);
      }

      return {
        success: true,
        data: newTemplate
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '创建课程安排模板失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 更新课程安排模板
   * @param id 模板ID
   * @param updateData 更新数据
   * @returns 更新后的模板信息
   */
  async updateTemplate(id: string, updateData: Omit<IScheduleTemplateUpdateRequest, 'id'>): Promise<OperationResult<IScheduleTemplate>> {
    try {
      // 获取现有模板列表
      const templatesResult = await this.getAllTemplates();
      if (!templatesResult.success) {
        return templatesResult;
      }

      const templates = templatesResult.data;
      const templateIndex = templates.findIndex(t => t.id === id);

      if (templateIndex === -1) {
        return {
          success: false,
          error: '课程安排模板不存在'
        };
      }

      const existingTemplate = templates[templateIndex];

      // 合并更新数据
      const updatedTemplate: IScheduleTemplate = {
        ...existingTemplate,
        ...updateData,
        id, // 确保ID不被修改
        updatedAt: Date.now()
      };

      // 验证更新后的数据
      const validationResult = this.validateTemplateData(updatedTemplate);
      if (!validationResult.isValid) {
        return {
          success: false,
          error: validationResult.errors.join('; ')
        };
      }

      // 如果更新了关键信息，重新计算结束日期
      if (updateData.startDate || updateData.dayOfWeek || updateData.totalCount) {
        updatedTemplate.endDate = this.calculateEndDate(
          updatedTemplate.startDate, 
          updatedTemplate.dayOfWeek, 
          updatedTemplate.totalCount
        );
      }

      // 更新模板列表
      templates[templateIndex] = updatedTemplate;

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.SCHEDULE_TEMPLATES, templates, {
        createBackup: true
      });

      if (!saveResult.success) {
        return saveResult;
      }

      // 如果更新了关键信息，重新生成实例
      if (updateData.startDate || updateData.dayOfWeek || updateData.totalCount || updateData.startTime || updateData.endTime) {
        await this.regenerateInstances(id);
      }

      return {
        success: true,
        data: updatedTemplate
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新课程安排模板失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 删除课程安排模板（软删除）
   * @param id 模板ID
   * @returns 操作结果
   */
  async deleteTemplate(id: string): Promise<OperationResult<void>> {
    try {
      // 软删除：将状态设置为已删除
      const updateResult = await this.updateTemplate(id, {
        status: ScheduleTemplateStatusEnum.DELETED
      });

      if (!updateResult.success) {
        return updateResult;
      }

      // 同时删除相关的课程实例
      await this.deleteInstancesByTemplate(id);

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '删除课程安排模板失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 生成课程实例
   * @param templateId 模板ID
   * @returns 操作结果
   */
  async generateInstances(templateId: string): Promise<OperationResult<IScheduleInstance[]>> {
    try {
      const templateResult = await this.getTemplateById(templateId);
      if (!templateResult.success) {
        return templateResult;
      }

      const template = templateResult.data;

      // 获取现有实例列表
      const instancesResult = await this.getAllInstances();
      if (!instancesResult.success) {
        return instancesResult;
      }

      let instances = instancesResult.data;

      // 删除该模板的现有实例
      instances = instances.filter(inst => inst.templateId !== templateId);

      // 生成新的实例
      const newInstances = this.generateInstancesFromTemplate(template);

      // 添加到实例列表
      instances.push(...newInstances);

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.SCHEDULE_INSTANCES, instances);
      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: newInstances
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '生成课程实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  // ==================== 课程实例相关方法 ====================

  /**
   * 获取所有课程实例
   * @param queryParams 查询参数
   * @returns 实例列表
   */
  async getAllInstances(queryParams?: IScheduleInstanceQueryParams): Promise<OperationResult<IScheduleInstance[]>> {
    try {
      const result = await storageService.getItem<IScheduleInstance[]>(STORAGE_KEYS.SCHEDULE_INSTANCES);
      
      if (!result.success) {
        // 如果没有数据，返回空数组
        if (result.errorCode === 'INVALID_DATA_FORMAT') {
          return {
            success: true,
            data: []
          };
        }
        return result;
      }

      let instances = result.data || [];

      // 过滤已删除的实例
      instances = instances.filter(instance => instance.status !== ScheduleInstanceStatusEnum.DELETED);

      // 应用查询参数
      if (queryParams) {
        instances = this.filterInstances(instances, queryParams);
      }

      return {
        success: true,
        data: instances
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程实例列表失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据ID获取课程实例
   * @param id 实例ID
   * @returns 实例信息
   */
  async getInstanceById(id: string): Promise<OperationResult<IScheduleInstance>> {
    try {
      const instancesResult = await this.getAllInstances();
      if (!instancesResult.success) {
        return instancesResult;
      }

      const instance = instancesResult.data.find(i => i.id === id);
      if (!instance) {
        return {
          success: false,
          error: '课程实例不存在'
        };
      }

      return {
        success: true,
        data: instance
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程实例信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据模板ID获取课程实例
   * @param templateId 模板ID
   * @returns 实例列表
   */
  async getInstancesByTemplate(templateId: string): Promise<OperationResult<IScheduleInstance[]>> {
    try {
      const instancesResult = await this.getAllInstances({
        templateId
      });

      return instancesResult;

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取模板课程实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据日期获取课程实例
   * @param date 日期
   * @param studentIds 学生ID列表（可选）
   * @returns 实例列表
   */
  async getInstancesByDate(date: string, studentIds?: string[]): Promise<OperationResult<IScheduleInstance[]>> {
    try {
      const queryParams: IScheduleInstanceQueryParams = {
        date
      };

      if (studentIds && studentIds.length > 0) {
        queryParams.studentIds = studentIds;
      }

      const instancesResult = await this.getAllInstances(queryParams);
      return instancesResult;

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取日期课程实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据日期范围获取课程实例
   * @param dateFrom 开始日期
   * @param dateTo 结束日期
   * @param studentIds 学生ID列表（可选）
   * @returns 实例列表
   */
  async getInstancesByDateRange(dateFrom: string, dateTo: string, studentIds?: string[]): Promise<OperationResult<IScheduleInstance[]>> {
    try {
      const queryParams: IScheduleInstanceQueryParams = {
        dateFrom,
        dateTo
      };

      if (studentIds && studentIds.length > 0) {
        queryParams.studentIds = studentIds;
      }

      const instancesResult = await this.getAllInstances(queryParams);
      return instancesResult;

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取日期范围课程实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 更新课程实例
   * @param id 实例ID
   * @param updateData 更新数据
   * @returns 更新后的实例信息
   */
  async updateInstance(id: string, updateData: Omit<IScheduleInstanceUpdateRequest, 'id'>): Promise<OperationResult<IScheduleInstance>> {
    try {
      // 获取现有实例列表
      const instancesResult = await this.getAllInstances();
      if (!instancesResult.success) {
        return instancesResult;
      }

      const instances = instancesResult.data;
      const instanceIndex = instances.findIndex(i => i.id === id);

      if (instanceIndex === -1) {
        return {
          success: false,
          error: '课程实例不存在'
        };
      }

      const existingInstance = instances[instanceIndex];

      // 合并更新数据
      const updatedInstance: IScheduleInstance = {
        ...existingInstance,
        ...updateData,
        id, // 确保ID不被修改
        updatedAt: Date.now()
      };

      // 更新实例列表
      instances[instanceIndex] = updatedInstance;

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.SCHEDULE_INSTANCES, instances);
      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: updatedInstance
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新课程实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 完成课程实例
   * @param id 实例ID
   * @returns 操作结果
   */
  async completeInstance(id: string): Promise<OperationResult<IScheduleInstance>> {
    try {
      const instanceResult = await this.getInstanceById(id);
      if (!instanceResult.success) {
        return instanceResult;
      }

      const instance = instanceResult.data;

      // 更新实例状态
      const updateResult = await this.updateInstance(id, {
        status: ScheduleInstanceStatusEnum.COMPLETED,
        attendanceStatus: 'present'
      });

      if (!updateResult.success) {
        return updateResult;
      }

      // 更新模板的完成次数
      await this.updateTemplateCompletedCount(instance.templateId, 1);

      return updateResult;

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '完成课程实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 取消课程实例
   * @param id 实例ID
   * @param reason 取消原因
   * @returns 操作结果
   */
  async cancelInstance(id: string, reason?: string): Promise<OperationResult<IScheduleInstance>> {
    try {
      const instanceResult = await this.getInstanceById(id);
      if (!instanceResult.success) {
        return instanceResult;
      }

      const instance = instanceResult.data;

      // 更新实例状态
      const updateResult = await this.updateInstance(id, {
        status: ScheduleInstanceStatusEnum.CANCELLED,
        cancelReason: reason
      });

      if (!updateResult.success) {
        return updateResult;
      }

      // 更新模板的取消次数
      await this.updateTemplateCancelledCount(instance.templateId, 1);

      return updateResult;

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '取消课程实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 添加补课实例
   * @param templateId 模板ID
   * @param date 补课日期
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @returns 操作结果
   */
  async addMakeupInstance(
    templateId: string, 
    date: string, 
    startTime?: string, 
    endTime?: string
  ): Promise<OperationResult<IScheduleInstance>> {
    try {
      const templateResult = await this.getTemplateById(templateId);
      if (!templateResult.success) {
        return templateResult;
      }

      const template = templateResult.data;

      // 检查是否允许补课
      if (!template.allowMakeup) {
        return {
          success: false,
          error: '该课程不允许补课'
        };
      }

      // 检查补课次数限制
      if (template.maxMakeupCount && template.currentMakeupCount >= template.maxMakeupCount) {
        return {
          success: false,
          error: `补课次数已达上限（${template.maxMakeupCount}次）`
        };
      }

      // 检查时间冲突
      const conflictResult = await this.checkInstanceConflict({
        templateId,
        studentId: template.studentId,
        courseId: template.courseId,
        date,
        startTime: startTime || template.startTime,
        endTime: endTime || template.endTime,
        sequenceNumber: 0, // 补课不计入序号
        status: ScheduleInstanceStatusEnum.MAKEUP,
        isMakeup: true
      });

      if (!conflictResult.success) {
        return conflictResult;
      }

      if (conflictResult.data.hasConflict) {
        return {
          success: false,
          error: `时间冲突：${conflictResult.data.conflicts.map(c => c.description).join('; ')}`
        };
      }

      // 创建补课实例
      const now = Date.now();
      const makeupInstance: IScheduleInstance = {
        id: this.generateInstanceId(),
        templateId,
        studentId: template.studentId,
        courseId: template.courseId,
        date,
        startTime: startTime || template.startTime,
        endTime: endTime || template.endTime,
        sequenceNumber: 0, // 补课不计入序号
        location: template.location,
        status: ScheduleInstanceStatusEnum.MAKEUP,
        isMakeup: true,
        createdAt: now,
        updatedAt: now
      };

      // 获取现有实例列表
      const instancesResult = await this.getAllInstances();
      if (!instancesResult.success) {
        return instancesResult;
      }

      const instances = instancesResult.data;
      instances.push(makeupInstance);

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.SCHEDULE_INSTANCES, instances);
      if (!saveResult.success) {
        return saveResult;
      }

      // 更新模板的补课次数
      await this.updateTemplateMakeupCount(templateId, 1);

      return {
        success: true,
        data: makeupInstance
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '添加补课实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  // ==================== 冲突检测相关方法 ====================

  /**
   * 检查模板时间冲突
   * @param templateData 模板数据
   * @returns 冲突检测结果
   */
  async checkTemplateConflict(templateData: IScheduleTemplateCreateRequest): Promise<OperationResult<IConflictDetectionResult>> {
    try {
      const templatesResult = await this.getAllTemplates();
      if (!templatesResult.success) {
        return templatesResult;
      }

      const existingTemplates = templatesResult.data.filter(t => 
        t.studentId === templateData.studentId && 
        t.status === ScheduleTemplateStatusEnum.ACTIVE
      );

      const conflicts: IScheduleInstanceConflict[] = [];

      for (const existingTemplate of existingTemplates) {
        // 检查星期是否相同
        if (existingTemplate.dayOfWeek === templateData.dayOfWeek) {
          // 检查时间是否重叠
          if (this.isTimeOverlap(
            templateData.startTime, 
            templateData.endTime,
            existingTemplate.startTime, 
            existingTemplate.endTime
          )) {
            conflicts.push({
              instanceId: existingTemplate.id,
              studentId: existingTemplate.studentId,
              studentName: '学生', // 这里可以从学生数据中获取
              courseId: existingTemplate.courseId,
              courseName: '课程', // 这里可以从课程数据中获取
              date: `每${this.getDayOfWeekText(existingTemplate.dayOfWeek)}`,
              timeRange: `${existingTemplate.startTime}-${existingTemplate.endTime}`,
              conflictType: 'time_overlap',
              description: `与现有课程时间冲突`
            });
          }
        }
      }

      return {
        success: true,
        data: {
          hasConflict: conflicts.length > 0,
          conflicts
        }
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '检查模板冲突失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 检查实例时间冲突
   * @param instanceData 实例数据
   * @returns 冲突检测结果
   */
  async checkInstanceConflict(instanceData: IScheduleInstanceCreateRequest): Promise<OperationResult<IConflictDetectionResult>> {
    try {
      const instancesResult = await this.getAllInstances({
        studentId: instanceData.studentId,
        date: instanceData.date
      });

      if (!instancesResult.success) {
        return instancesResult;
      }

      const existingInstances = instancesResult.data.filter(inst => 
        inst.status !== ScheduleInstanceStatusEnum.CANCELLED &&
        inst.status !== ScheduleInstanceStatusEnum.DELETED
      );

      const conflicts: IScheduleInstanceConflict[] = [];

      for (const existingInstance of existingInstances) {
        // 检查时间是否重叠
        if (this.isTimeOverlap(
          instanceData.startTime, 
          instanceData.endTime,
          existingInstance.startTime, 
          existingInstance.endTime
        )) {
          conflicts.push({
            instanceId: existingInstance.id,
            studentId: existingInstance.studentId,
            studentName: '学生', // 这里可以从学生数据中获取
            courseId: existingInstance.courseId,
            courseName: '课程', // 这里可以从课程数据中获取
            date: existingInstance.date,
            timeRange: `${existingInstance.startTime}-${existingInstance.endTime}`,
            conflictType: 'time_overlap',
            description: `与 ${existingInstance.date} 的课程时间冲突`
          });
        }
      }

      return {
        success: true,
        data: {
          hasConflict: conflicts.length > 0,
          conflicts
        }
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '检查实例冲突失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  // ==================== 私有辅助方法 ====================

  /**
   * 验证模板数据
   * @param templateData 模板数据
   * @returns 验证结果
   */
  private validateTemplateData(templateData: Partial<IScheduleTemplate>): IScheduleValidationResult {
    const errors: string[] = [];

    // 必填字段验证
    if (!templateData.studentId) {
      errors.push('学生ID不能为空');
    }

    if (!templateData.courseId) {
      errors.push('课程ID不能为空');
    }

    if (!templateData.startDate) {
      errors.push('开始日期不能为空');
    }

    if (!templateData.startTime) {
      errors.push('开始时间不能为空');
    }

    if (!templateData.endTime) {
      errors.push('结束时间不能为空');
    }

    if (!templateData.dayOfWeek) {
      errors.push('星期不能为空');
    }

    if (!templateData.totalCount || templateData.totalCount <= 0) {
      errors.push('总次数必须大于0');
    }

    // 时间格式验证
    if (templateData.startTime && !/^\d{2}:\d{2}$/.test(templateData.startTime)) {
      errors.push('开始时间格式不正确（应为HH:MM）');
    }

    if (templateData.endTime && !/^\d{2}:\d{2}$/.test(templateData.endTime)) {
      errors.push('结束时间格式不正确（应为HH:MM）');
    }

    // 时间逻辑验证
    if (templateData.startTime && templateData.endTime) {
      if (templateData.startTime >= templateData.endTime) {
        errors.push('开始时间必须早于结束时间');
      }
    }

    // 日期格式验证
    if (templateData.startDate && !/^\d{4}-\d{2}-\d{2}$/.test(templateData.startDate)) {
      errors.push('开始日期格式不正确（应为YYYY-MM-DD）');
    }

    // 星期验证
    if (templateData.dayOfWeek && (templateData.dayOfWeek < 1 || templateData.dayOfWeek > 7)) {
      errors.push('星期必须在1-7之间');
    }

    // 次数验证
    if (templateData.totalCount && templateData.totalCount > 1000) {
      errors.push('总次数不能超过1000');
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * 验证学生和课程是否存在
   * @param studentId 学生ID
   * @param courseId 课程ID
   * @returns 验证结果
   */
  private async validateStudentAndCourse(studentId: string, courseId: string): Promise<OperationResult<void>> {
    try {
      // 验证学生是否存在
      const studentsResult = await storageService.getItem(STORAGE_KEYS.STUDENTS);
      if (studentsResult.success && studentsResult.data) {
        const students = Array.isArray(studentsResult.data) ? studentsResult.data : [];
        const studentExists = students.some((s: any) => s.id === studentId);
        if (!studentExists) {
          return {
            success: false,
            error: '指定的学生不存在'
          };
        }
      }

      // 验证课程是否存在
      const coursesResult = await storageService.getItem(STORAGE_KEYS.COURSES);
      if (coursesResult.success && coursesResult.data) {
        const courses = Array.isArray(coursesResult.data) ? coursesResult.data : [];
        const courseExists = courses.some((c: any) => c.id === courseId);
        if (!courseExists) {
          return {
            success: false,
            error: '指定的课程不存在'
          };
        }
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '验证学生和课程失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 过滤模板列表
   * @param templates 模板列表
   * @param queryParams 查询参数
   * @returns 过滤后的模板列表
   */
  private filterTemplates(templates: IScheduleTemplate[], queryParams: IScheduleTemplateQueryParams): IScheduleTemplate[] {
    return templates.filter(template => {
      // 学生ID匹配
      if (queryParams.studentId && template.studentId !== queryParams.studentId) {
        return false;
      }

      if (queryParams.studentIds && !queryParams.studentIds.includes(template.studentId)) {
        return false;
      }

      // 课程ID匹配
      if (queryParams.courseId && template.courseId !== queryParams.courseId) {
        return false;
      }

      if (queryParams.courseIds && !queryParams.courseIds.includes(template.courseId)) {
        return false;
      }

      // 星期匹配
      if (queryParams.dayOfWeek && template.dayOfWeek !== queryParams.dayOfWeek) {
        return false;
      }

      if (queryParams.dayOfWeeks && !queryParams.dayOfWeeks.includes(template.dayOfWeek)) {
        return false;
      }

      // 状态匹配
      if (queryParams.status && template.status !== queryParams.status) {
        return false;
      }

      if (queryParams.statuses && !queryParams.statuses.includes(template.status)) {
        return false;
      }

      // 日期范围匹配
      if (queryParams.startDateFrom && template.startDate < queryParams.startDateFrom) {
        return false;
      }

      if (queryParams.startDateTo && template.startDate > queryParams.startDateTo) {
        return false;
      }

      // 时间范围匹配
      if (queryParams.timeFrom && template.startTime < queryParams.timeFrom) {
        return false;
      }

      if (queryParams.timeTo && template.endTime > queryParams.timeTo) {
        return false;
      }

      // 地点匹配
      if (queryParams.location && template.location !== queryParams.location) {
        return false;
      }

      // 补课设置匹配
      if (queryParams.allowMakeup !== undefined && template.allowMakeup !== queryParams.allowMakeup) {
        return false;
      }

      // 剩余次数匹配
      if (queryParams.hasRemainingCount !== undefined) {
        const hasRemaining = (template.totalCount - template.completedCount) > 0;
        if (queryParams.hasRemainingCount !== hasRemaining) {
          return false;
        }
      }

      return true;
    });
  }

  /**
   * 过滤实例列表
   * @param instances 实例列表
   * @param queryParams 查询参数
   * @returns 过滤后的实例列表
   */
  private filterInstances(instances: IScheduleInstance[], queryParams: IScheduleInstanceQueryParams): IScheduleInstance[] {
    return instances.filter(instance => {
      // 模板ID匹配
      if (queryParams.templateId && instance.templateId !== queryParams.templateId) {
        return false;
      }

      if (queryParams.templateIds && !queryParams.templateIds.includes(instance.templateId)) {
        return false;
      }

      // 学生ID匹配
      if (queryParams.studentId && instance.studentId !== queryParams.studentId) {
        return false;
      }

      if (queryParams.studentIds && !queryParams.studentIds.includes(instance.studentId)) {
        return false;
      }

      // 课程ID匹配
      if (queryParams.courseId && instance.courseId !== queryParams.courseId) {
        return false;
      }

      if (queryParams.courseIds && !queryParams.courseIds.includes(instance.courseId)) {
        return false;
      }

      // 日期匹配
      if (queryParams.date && instance.date !== queryParams.date) {
        return false;
      }

      if (queryParams.dates && !queryParams.dates.includes(instance.date)) {
        return false;
      }

      // 日期范围匹配
      if (queryParams.dateFrom && instance.date < queryParams.dateFrom) {
        return false;
      }

      if (queryParams.dateTo && instance.date > queryParams.dateTo) {
        return false;
      }

      // 时间范围匹配
      if (queryParams.timeFrom && instance.startTime < queryParams.timeFrom) {
        return false;
      }

      if (queryParams.timeTo && instance.endTime > queryParams.timeTo) {
        return false;
      }

      // 状态匹配
      if (queryParams.status && instance.status !== queryParams.status) {
        return false;
      }

      if (queryParams.statuses && !queryParams.statuses.includes(instance.status)) {
        return false;
      }

      // 补课匹配
      if (queryParams.isMakeup !== undefined && instance.isMakeup !== queryParams.isMakeup) {
        return false;
      }

      // 出勤状态匹配
      if (queryParams.attendanceStatus && instance.attendanceStatus !== queryParams.attendanceStatus) {
        return false;
      }

      // 支付状态匹配
      if (queryParams.paymentStatus && instance.paymentStatus !== queryParams.paymentStatus) {
        return false;
      }

      // 地点匹配
      if (queryParams.location && instance.location !== queryParams.location) {
        return false;
      }

      // 序号范围匹配
      if (queryParams.minSequenceNumber && instance.sequenceNumber < queryParams.minSequenceNumber) {
        return false;
      }

      if (queryParams.maxSequenceNumber && instance.sequenceNumber > queryParams.maxSequenceNumber) {
        return false;
      }

      return true;
    });
  }

  /**
   * 从模板生成实例
   * @param template 模板
   * @returns 实例列表
   */
  private generateInstancesFromTemplate(template: IScheduleTemplate): IScheduleInstance[] {
    const instances: IScheduleInstance[] = [];
    const startDate = new Date(template.startDate);

    for (let i = 0; i < template.totalCount; i++) {
      const instanceDate = this.calculateInstanceDate(startDate, template.dayOfWeek, i);
      
      const instance: IScheduleInstance = {
        id: this.generateInstanceId(),
        templateId: template.id,
        studentId: template.studentId,
        courseId: template.courseId,
        date: this.formatDate(instanceDate),
        startTime: template.startTime,
        endTime: template.endTime,
        sequenceNumber: i + 1,
        location: template.location,
        remark: template.remark,
        status: ScheduleInstanceStatusEnum.SCHEDULED,
        isMakeup: false,
        createdAt: Date.now(),
        updatedAt: Date.now()
      };

      instances.push(instance);
    }

    return instances;
  }

  /**
   * 计算实例日期
   * @param startDate 开始日期
   * @param targetDayOfWeek 目标星期
   * @param weekOffset 周偏移
   * @returns 实例日期
   */
  private calculateInstanceDate(startDate: Date, targetDayOfWeek: DayOfWeekEnum, weekOffset: number): Date {
    const startDayOfWeek = startDate.getDay() || 7; // 转换为1-7格式
    const daysToAdd = (targetDayOfWeek - startDayOfWeek + 7) % 7 + (weekOffset * 7);
    
    const instanceDate = new Date(startDate);
    instanceDate.setDate(startDate.getDate() + daysToAdd);
    
    return instanceDate;
  }

  /**
   * 计算结束日期
   * @param startDate 开始日期
   * @param dayOfWeek 星期
   * @param totalCount 总次数
   * @returns 结束日期
   */
  private calculateEndDate(startDate: string, dayOfWeek: DayOfWeekEnum, totalCount: number): string {
    const start = new Date(startDate);
    const endDate = this.calculateInstanceDate(start, dayOfWeek, totalCount - 1);
    return this.formatDate(endDate);
  }

  /**
   * 计算下次上课日期
   * @param template 模板
   * @param instances 实例列表
   * @returns 下次上课日期
   */
  private calculateNextSessionDate(template: IScheduleTemplate, instances: IScheduleInstance[]): string | undefined {
    const now = new Date();
    const today = this.formatDate(now);

    // 找到未来的已安排实例
    const futureInstances = instances.filter(inst => 
      inst.date >= today && 
      inst.status === ScheduleInstanceStatusEnum.SCHEDULED
    );

    if (futureInstances.length === 0) {
      return undefined;
    }

    // 按日期排序，返回最近的一个
    futureInstances.sort((a, b) => a.date.localeCompare(b.date));
    return futureInstances[0].date;
  }

  /**
   * 检查时间是否重叠
   * @param startTime1 时间1开始
   * @param endTime1 时间1结束
   * @param startTime2 时间2开始
   * @param endTime2 时间2结束
   * @returns 是否重叠
   */
  private isTimeOverlap(startTime1: string, endTime1: string, startTime2: string, endTime2: string): boolean {
    return startTime1 < endTime2 && endTime1 > startTime2;
  }

  /**
   * 获取星期文本
   * @param dayOfWeek 星期枚举
   * @returns 星期文本
   */
  private getDayOfWeekText(dayOfWeek: DayOfWeekEnum): string {
    const dayTexts = {
      [DayOfWeekEnum.MONDAY]: '周一',
      [DayOfWeekEnum.TUESDAY]: '周二',
      [DayOfWeekEnum.WEDNESDAY]: '周三',
      [DayOfWeekEnum.THURSDAY]: '周四',
      [DayOfWeekEnum.FRIDAY]: '周五',
      [DayOfWeekEnum.SATURDAY]: '周六',
      [DayOfWeekEnum.SUNDAY]: '周日'
    };
    return dayTexts[dayOfWeek] || '未知';
  }

  /**
   * 格式化日期
   * @param date 日期对象
   * @returns 格式化的日期字符串
   */
  private formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  /**
   * 重新生成实例
   * @param templateId 模板ID
   * @returns 操作结果
   */
  private async regenerateInstances(templateId: string): Promise<OperationResult<void>> {
    try {
      // 删除现有实例
      await this.deleteInstancesByTemplate(templateId);
      
      // 重新生成实例
      await this.generateInstances(templateId);

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '重新生成实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 删除模板的所有实例
   * @param templateId 模板ID
   * @returns 操作结果
   */
  private async deleteInstancesByTemplate(templateId: string): Promise<OperationResult<void>> {
    try {
      const instancesResult = await this.getAllInstances();
      if (!instancesResult.success) {
        return instancesResult;
      }

      const instances = instancesResult.data.filter(inst => inst.templateId !== templateId);

      const saveResult = await storageService.setItem(STORAGE_KEYS.SCHEDULE_INSTANCES, instances);
      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '删除模板实例失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 更新模板完成次数
   * @param templateId 模板ID
   * @param increment 增量
   * @returns 操作结果
   */
  private async updateTemplateCompletedCount(templateId: string, increment: number): Promise<OperationResult<void>> {
    try {
      const templateResult = await this.getTemplateById(templateId);
      if (!templateResult.success) {
        return templateResult;
      }

      const template = templateResult.data;
      const newCompletedCount = template.completedCount + increment;

      // 检查是否完成所有课程
      let newStatus = template.status;
      if (newCompletedCount >= template.totalCount && template.status === ScheduleTemplateStatusEnum.ACTIVE) {
        newStatus = ScheduleTemplateStatusEnum.COMPLETED;
      }

      // 直接更新模板数据，因为 updateTemplate 的类型定义不包含这些字段
      const templatesResult = await this.getAllTemplates();
      if (templatesResult.success) {
        const templates = templatesResult.data;
        const templateIndex = templates.findIndex(t => t.id === templateId);
        if (templateIndex !== -1) {
          templates[templateIndex].completedCount = newCompletedCount;
          templates[templateIndex].status = newStatus;
          templates[templateIndex].updatedAt = Date.now();
          await storageService.setItem(STORAGE_KEYS.SCHEDULE_TEMPLATES, templates);
        }
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新模板完成次数失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 更新模板取消次数
   * @param templateId 模板ID
   * @param increment 增量
   * @returns 操作结果
   */
  private async updateTemplateCancelledCount(templateId: string, increment: number): Promise<OperationResult<void>> {
    try {
      const templateResult = await this.getTemplateById(templateId);
      if (!templateResult.success) {
        return templateResult;
      }

      const template = templateResult.data;
      const newCancelledCount = template.cancelledCount + increment;

      // 直接更新模板数据
      const templatesResult = await this.getAllTemplates();
      if (templatesResult.success) {
        const templates = templatesResult.data;
        const templateIndex = templates.findIndex(t => t.id === templateId);
        if (templateIndex !== -1) {
          templates[templateIndex].cancelledCount = newCancelledCount;
          templates[templateIndex].updatedAt = Date.now();
          await storageService.setItem(STORAGE_KEYS.SCHEDULE_TEMPLATES, templates);
        }
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新模板取消次数失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 更新模板补课次数
   * @param templateId 模板ID
   * @param increment 增量
   * @returns 操作结果
   */
  private async updateTemplateMakeupCount(templateId: string, increment: number): Promise<OperationResult<void>> {
    try {
      const templateResult = await this.getTemplateById(templateId);
      if (!templateResult.success) {
        return templateResult;
      }

      const template = templateResult.data;
      const newMakeupCount = template.currentMakeupCount + increment;

      // 直接更新模板数据
      const templatesResult = await this.getAllTemplates();
      if (templatesResult.success) {
        const templates = templatesResult.data;
        const templateIndex = templates.findIndex(t => t.id === templateId);
        if (templateIndex !== -1) {
          templates[templateIndex].currentMakeupCount = newMakeupCount;
          templates[templateIndex].updatedAt = Date.now();
          await storageService.setItem(STORAGE_KEYS.SCHEDULE_TEMPLATES, templates);
        }
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新模板补课次数失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 生成模板ID
   * @returns 模板ID
   */
  private generateTemplateId(): string {
    const timestamp = Date.now().toString(36);
    const randomStr = Math.random().toString(36).substr(2, 9);
    return `template_${timestamp}_${randomStr}`;
  }

  /**
   * 生成实例ID
   * @returns 实例ID
   */
  private generateInstanceId(): string {
    const timestamp = Date.now().toString(36);
    const randomStr = Math.random().toString(36).substr(2, 9);
    return `instance_${timestamp}_${randomStr}`;
  }
}

/**
 * 默认课表服务实例
 */
export const scheduleService = new ScheduleService();